package com.sita.friend.ui.activity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMChatManager;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnClickListener;
import com.orhanobut.dialogplus.ViewHolder;
import com.sita.bike.R;
import com.sita.bike.beans.PersonBean;
import com.sita.bike.event.LogoutEvent;
import com.sita.bike.services.XmppBackgroundService;
import com.sita.bike.support.GlobalContext;
import com.sita.bike.ui.activity.LoginActivity;
import com.sita.bike.ui.fragments.MainFragment;
import com.sita.bike.utils.LocalStorage;
import com.sita.bike.utils.PersistUtils;
import com.sita.bike.utils.SessionUtils;
import com.sita.friend.Constant;
import com.sita.tboard.ActivityBase;
import com.sita.tboard.ui.fragment.MapSpeedDashboardFragment;
import com.sita.tboard.ui.tools.L;
import com.sita.tboard.version.CheckUpdateListener;
import com.sita.tboard.version.UpdateChecker;
import com.sita.tboard.version.UpdateNoticeStyle;
import com.sita.tboard.version.rest.VersionCheckHelper;
import com.sita.tboard.version.rest.VersionModule;

import java.util.List;

import app.akexorcist.bluetotohspp.library.BluetoothState;
import de.greenrobot.event.EventBus;

public class MainActivity extends ActivityBase {
    protected static final String TAG = MainActivity.class.getSimpleName();

    public String addressBlue;

    // TODO: 2015/12/29
    // 账号在别处登录
    public boolean isConflict = false;
    // 账号被移除
    private boolean isCurrentAccountRemoved = false;
    private PersonBean personBean;
    private ServiceConnection connection;
    private String userName;
    private boolean mIsEnterFromMain;
    private int playCount = 0;
    private static MainActivity instance;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        if(!LocalStorage.getWakeupFromBackground()){
//            checkWakeUpFromBackground();
//        }
        instance = this;
        SessionUtils.login();

//        if (savedInstanceState != null && savedInstanceState.getBoolean(Constant.ACCOUNT_REMOVED, false)) {
//            // 防止被移除后，没点确定按钮然后按了home键，长期在后台又进app导致的crash
//            // 三个fragment里加的判断同理
//            FriendHelper.getInstance().logout(true, null);
//            finish();
//            startActivity(new Intent(getApplicationContext(), LoginActivity.class));
//            return;
//        } else if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false)) {
//            // 防止被T后，没点确定按钮然后按了home键，长期在后台又进app导致的crash
//            // 三个fragment里加的判断同理
//            finish();
//            startActivity(new Intent(getApplicationContext(), LoginActivity.class));
//            return;
//        }
        setContentView(R.layout.activity_main_home);

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        if (personBean == null) {
            personBean = PersistUtils.findPersonBean();
        }

        String xmppUser = personBean.credential.getXmppUser();
        String xmppPass = personBean.credential.getXmppPass();
        if (xmppUser != null && xmppPass != null) {
            doStartXmppService();
        }

        FragmentTransaction ftx = getSupportFragmentManager().beginTransaction();
        if (!MainFragment.getInstance().isAdded()) {
            ftx.replace(R.id.main_home_fragment_container, MainFragment.getInstance(), "MainFragment");
            ftx.addToBackStack(null);
            ftx.commit();
        } else {
            finish();
        }

        // TODO: 2015/12/29 check accounts status
//        if (getIntent().getBooleanExtra(Constant.ACCOUNT_CONFLICT, false) && !isConflictDialogShow) {
//            showConflictDialog();
//        } else if (getIntent().getBooleanExtra(Constant.ACCOUNT_REMOVED, false) && !isAccountRemovedDialogShow) {
//            showAccountRemovedDialog();
//        }

        registerBroadcastReceiver();

        if (UpdateChecker.isNetworkAvailable(this)){
            UpdateChecker.checkUpdate(MainActivity.this, UpdateNoticeStyle.DIALOG_NOTIFICATION);
        }
    }

    private void registerBroadcastReceiver() {
        broadcastManager = LocalBroadcastManager.getInstance(getApplicationContext());
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_CONTACT_CHANAGED);
        intentFilter.addAction(Constant.ACTION_GROUP_CHANAGED);
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                //updateUnreadLabel();
//                updateUnreadAddressLable();
//                if (currentTabIndex == 0) {
//                    // 当前页面如果为聊天历史页面，刷新此页面
//                    if (conversationListFragment != null) {
//                        conversationListFragment.refresh();
//                    }
//                } else if (currentTabIndex == 1) {
//                    if (friendListFragment != null) {
//                        friendListFragment.refresh();
//                    }
//                }
//                String action = intent.getAction();
//                if (action.equals(Constant.ACTION_GROUP_CHANAGED)) {
//                    if (EaseCommonUtils.getTopActivity(getApplicationContext()).equals(GroupsActivity.class.getName())) {
//                        GroupsActivity.instance.onResume();
//                    }
//                }
            }
        };
        broadcastManager.registerReceiver(broadcastReceiver, intentFilter);
    }

    private void unregisterBroadcastReceiver() {
        broadcastManager.unregisterReceiver(broadcastReceiver);
    }


    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == BluetoothState.REQUEST_ENABLE_BT ||
                requestCode == BluetoothState.REQUEST_CONNECT_DEVICE) {
            MainFragment mainFragment = (MainFragment) getSupportFragmentManager().findFragmentByTag("MainFragment");
            MapSpeedDashboardFragment mapSpeedDashboardFragment = (MapSpeedDashboardFragment) mainFragment.getMapFragment();
            mapSpeedDashboardFragment.handleActivityResult(requestCode, resultCode, data);
        }
    }

    private void showTrendFragment(String resourceId) {
        MainFragment mainFragment = (MainFragment) getSupportFragmentManager().findFragmentByTag("MainFragment");
        mainFragment.showTrends(resourceId);
    }


    // TODO: 2015/12/29
    /**
     * 显示帐号在别处登录dialog
     */
//    private void showConflictDialog() {
//        isConflictDialogShow = true;
//        FriendHelper.getInstance().logout(false, null);
//        String st = getResources().getString(R.string.Logoff_notification);
//        if (!RoadTrustMainActivity.this.isFinishing()) {
//            // clear up global variables
//            try {
//                if (conflictBuilder == null)
//                    conflictBuilder = new android.app.AlertDialog.Builder(RoadTrustMainActivity.this);
//                conflictBuilder.setTitle(st);
//                conflictBuilder.setMessage(R.string.connect_conflict);
//                conflictBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
//
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//                        conflictBuilder = null;
//                        finish();
//                        startActivity(new Intent(RoadTrustMainActivity.this, LoginActivity.class));
//                    }
//                });
//                conflictBuilder.setCancelable(false);
//                conflictBuilder.create().show();
//                isConflict = true;
//            } catch (Exception e) {
//                EMLog.e(TAG, "---------color conflictBuilder error" + e.getMessage());
//            }
//
//        }
//
//    }

    // TODO: 2015/12/29

    /**
     * 帐号被移除的dialog
     */
//    private void showAccountRemovedDialog() {
//        isAccountRemovedDialogShow = true;
//        FriendHelper.getInstance().logout(true, null);
//        String st5 = getResources().getString(R.string.Remove_the_notification);
//        if (!RoadTrustMainActivity.this.isFinishing()) {
//            // clear up global variables
//            try {
//                if (accountRemovedBuilder == null)
//                    accountRemovedBuilder = new android.app.AlertDialog.Builder(RoadTrustMainActivity.this);
//                accountRemovedBuilder.setTitle(st5);
//                accountRemovedBuilder.setMessage(R.string.em_user_remove);
//                accountRemovedBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
//
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//                        accountRemovedBuilder = null;
//                        finish();
//                        startActivity(new Intent(RoadTrustMainActivity.this, LoginActivity.class));
//                    }
//                });
//                accountRemovedBuilder.setCancelable(false);
//                accountRemovedBuilder.create().show();
//                isCurrentAccountRemoved = true;
//            } catch (Exception e) {
//                EMLog.e(TAG, "---------color userRemovedBuilder error" + e.getMessage());
//            }
//
//        }
//
//    }
    private void doStartXmppService() {
        Intent intent = new Intent(getApplicationContext(), XmppBackgroundService.class);

        Log.d(TAG, "xmpp account is " + personBean.credential.getXmppUser() + "/" + personBean.credential.getXmppPass());

        connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                Log.d("LOG", "Activity ->Connected the Service");
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                Log.d("LOG", "Activity ->Disconnected the LocalService");
            }
        };

        getApplication().startService(intent);
        bindService(intent, connection, BIND_AUTO_CREATE);
        Log.d(TAG, "XmppService is started and binded to TinterestActivity");
    }

    private void doStopService() {
        if (connection != null) {
            unbindService(connection);
            connection = null;
        }
        Intent intent = new Intent(getApplicationContext(), XmppBackgroundService.class);
        getApplication().stopService(intent);
        Log.d(TAG, "Xmpp Service is stopped and unbinded to TinterestActivity");
    }

    protected void exitAppComplete() {
        doStopService();
        super.exitAppComplete();
    }

    private android.app.AlertDialog.Builder conflictBuilder;
    private android.app.AlertDialog.Builder accountRemovedBuilder;
    private boolean isConflictDialogShow;
    private boolean isAccountRemovedDialogShow;
    private BroadcastReceiver internalDebugReceiver;
    private BroadcastReceiver broadcastReceiver;
    private LocalBroadcastManager broadcastManager;

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (conflictBuilder != null) {
            conflictBuilder.create().dismiss();
            conflictBuilder = null;
        }

        doStopService();
        unregisterBroadcastReceiver();
        EventBus.getDefault().unregister(this);

        try {
            unregisterReceiver(internalDebugReceiver);
        } catch (Exception e) {
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }

    @Override
    public void onResume() {
        super.onResume();
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String action = bundle.getString("action");
            switch (action) {
                case "notifyNewTrend": {
                    String resourceId = bundle.getString("resourceId");
                    // TODO: 2016/4/12 show trends fragment
                    showTrendFragment(resourceId);
                    break;
                }
            }
        }

        // TODO: 2016/2/29 should remove where 
//        AccountUtils.getMileageInfoAsync();
//        AccountUtils.getRankingInfoAsync();
        //
        // TODO: 2015/12/29
//        if (!isConflict && !isCurrentAccountRemoved) {
//            updateUnreadLabel();
//            updateUnreadAddressLable();
//        }

        // unregister this event listener when this activity enters the
        // background
//        FriendHelper sdkHelper = FriendHelper.getInstance();
//        sdkHelper.pushActivity(this);

//        // register the event listener when enter the foreground
//        EMChatManager.getInstance().registerEventListener(this,
//                new EMNotifierEvent.Event[]{EMNotifierEvent.Event.EventNewMessage, EMNotifierEvent.Event.EventOfflineMessage, EMNotifierEvent.Event.EventConversationListChanged});
    }

    @Override
    public void onPause() {
        LocalStorage.setWakeupFromBackground(false);
        super.onPause();
    }

    public void onEvent(LogoutEvent event) {
        SessionUtils.logout();
        EMChatManager.getInstance().logout();
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    private static Boolean isQuit = false;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isQuit = false;
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!isQuit) {
                isQuit = true;
                Toast.makeText(getApplicationContext(), R.string.again_to_exit_app,
                        Toast.LENGTH_SHORT).show();
                // 利用handler延迟发送更改状态信息
                mHandler.sendEmptyMessageDelayed(0, 1000);
            } else {
                exitAppComplete();
            }
        }
        return false;
    }

    public static MainActivity getInstance() {
        return instance;
    }

}